﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace Weazel.Willows.Model
{
	public class Type : BasicType
	{
		private static int uniqueNumberGenerator = 0;
		private static string getUniqueTypeName()
		{
			return "Type" + (uniqueNumberGenerator++).ToString();
		}

		private string baseTypeName;

		private BasicType baseType;
		public BasicType BaseType
		{
			get { return baseType; }
		}

		private int width;
		public int Width
		{
			get { return width; }
		}

		public override int BitWidth
		{
			get
			{
				return baseType.BitWidth * width;
			}
		}

		public override bool IsSimpleType
		{
			get 
			{ 
				return baseType.IsSimpleType; 
			}
		}

		public Type(TypeRegistry registry, BasicType subType, int width)
			: base(registry, getUniqueTypeName())
		{
			this.baseType = subType;
			this.width = width;
			this.Resolved = true;
		}

		public Type(TypeRegistry registry, BasicType subType, int width, string name)
			: base(registry, name)
		{
			this.baseType = subType;
			this.width = width;
			this.Resolved = true;
		}

		public Type(TypeRegistry registry)
			: base(registry, null)
		{
			this.baseType = null;
		}

		public void Read(XmlElement description)
		{
			System.Diagnostics.Debug.Assert(description.Name == "TypeDef");

			System.Diagnostics.Debug.Assert(description.HasAttribute("name"));
			System.Diagnostics.Debug.Assert(description.HasAttribute("type"));
			System.Diagnostics.Debug.Assert(description.HasAttribute("width"));

			this.width = int.Parse(description.Attributes["width"].Value);
			this.Name = description.Attributes["name"].Value;
			this.baseTypeName = description.Attributes["type"].Value;
		}



		public override void Resolve()
		{
			if (Resolved)
				return;

			baseType = Registry[baseTypeName];
			Resolved = true;
		}

		public override string ToString()
		{
			return Name + " : " + baseType.Name + "(" + width + ")";
		}
	}
}
